// $Id$
package de.servicezombie.cxf;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.apache.cxf.message.Message;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.springframework.util.Assert;

class ServletApiAdapterCxf24Provider implements JaxrsServletApiAdapterProvider, JaxwsServletApiAdapterProvider {

	private Message message;
	private WebServiceContext context;

	public void setMessage(Message message) {
		this.message = message;
	}

	public ServletApiAdapter getServletApiAdapter() {
		
		if (message != null) {
			return getAdapterByJaxrsApi();
		}

		if (context != null) {
			return getAdapterByJaxwsApi();
		}

		throw new IllegalStateException("unable to determine configured framework");
	}

	private ServletApiAdapter getAdapterByJaxwsApi() {

		MessageContext msgContext = context.getMessageContext();

		ServletApiAdapterDefaultImpl instance = new ServletApiAdapterDefaultImpl();

		HttpServletResponse response = (HttpServletResponse) msgContext.get(MessageContext.SERVLET_RESPONSE);
		Assert.notNull(response, "No HttpServletResponse is available.");
		instance.servletResponse = response;

		HttpServletRequest request = (HttpServletRequest) msgContext.get(MessageContext.SERVLET_REQUEST);
		Assert.notNull(request, "No HttpServletRequest is available.");
		instance.servletRequest = request;

		ServletContext servletContext = (ServletContext) msgContext.get(MessageContext.SERVLET_CONTEXT);
		Assert.notNull(request, "No ServletContext is available.");
		instance.servletContext = servletContext;
		return instance;
	}

	private ServletApiAdapter getAdapterByJaxrsApi() {

		ServletApiAdapterDefaultImpl instance = new ServletApiAdapterDefaultImpl();

		HttpServletResponse servletResponse = (HttpServletResponse) message
				.getContextualProperty(AbstractHTTPDestination.HTTP_RESPONSE);
		JaxrsServletApiFactory.logIfNotNull(servletResponse, "No HttpServletResponse is available.");
		instance.servletResponse = servletResponse;

		HttpServletRequest servletRequest = (HttpServletRequest) message
				.getContextualProperty(AbstractHTTPDestination.HTTP_REQUEST);
		JaxrsServletApiFactory.logIfNotNull(servletRequest, "No HttpServletRequest is available.");
		instance.servletRequest = servletRequest;

		ServletContext servletContext = (ServletContext) message.getContextualProperty(AbstractHTTPDestination.HTTP_CONTEXT);
		JaxrsServletApiFactory.logIfNotNull(servletContext, "No ServletContext is available.");
		instance.servletContext = servletContext;

		return instance;
	}

	public void setContext(WebServiceContext context) {
		this.context = context;
	}
}
